package com.czr.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.czr.config.mybatis.KsdConstants;
import com.czr.entity.User;
import com.czr.entity.vo.UserVo;
import com.czr.service.user.UserService;
import com.czr.utils.pwd.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import com.google.code.kaptcha.Constants;
import javax.servlet.http.HttpSession;

/**
 * Description:
 * Author: czr czr
 * Version: 1.0
 * Create Date Time: 2021/11/20 18:26.
 * Update Date Time:
 *
 * @see
 */
@Controller
public class loginController {

    @Autowired
    private UserService userService;

    @GetMapping("/login")
    public String login(HttpSession session) {
        User user = (User)session.getAttribute(KsdConstants.SESSION_USER);
        if (user != null) {
            return "redirect:/";
        }

        return "login";
    }

    /*@GetMapping("/login1")
    public String login1(HttpSession session) {
        User user = (User)session.getAttribute(KsdConstants.SESSION_USER);
        if (user != null) {
            return "redirect:/";
        }

        return "login";
    }*/

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();

        return "redirect:/login";
    }

    @PostMapping("/logined")
    @ResponseBody
    public String logined(@RequestBody UserVo userVo, HttpSession session) {

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(User::getNickname, userVo.getNickname());

        User user = userService.getOne(queryWrapper);

        // 如果用户存在直接抛异常
        if (user == null) {
            return "fail";
        }

        // 判断验证码
        String codeing = (String)session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
        if (!userVo.getCode().equalsIgnoreCase(codeing)) {
            return "failcode";
        }

        // 把用户输入的密码进行加密
        String inputPwd = MD5Util.md5slat(userVo.getPassword());

        if (user.getPassword().equals(inputPwd)) {
            session.setAttribute(KsdConstants.SESSION_USER, user);
            return "success";
        }
        return "fail";
    }

}
